package main.controller;

import main.PathUtil;
import main.StringHelper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@RestController
public class UploadPageController {
    @PostMapping("/upload")
    public String singleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
            return "error";
        }

        try {
            String originalFilename = file.getOriginalFilename();
            int dot = originalFilename.lastIndexOf('.');
            String extension = file.getOriginalFilename().substring(dot + 1);

            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
            String destFileName = now.format(formatter) + StringHelper.getAlphaNumericString(8) + "." + extension;
            String filePath = PathUtil.PathPrefix + destFileName;
            File dest = new File(filePath);
            file.transferTo(dest);
//            byte[] bytes = file.getBytes();
//            Path path = Paths.get(filePath);
//            Files.write(path, bytes);

            return destFileName;

        } catch (IOException e) {
            e.printStackTrace();
        }

        return "error";
    }
}
